import {
  dsx
} from "../../tools/datax"
import {
  users
} from "../../tools/users"
import {
  ui
} from "../../tools/ui"
import {
  nav2
} from "../../tools/nav2"

Page({
  data: {
    user: null,
  },

  async onLoad(options) {
    ui.loading()
    const user = await this.loadUser()
    const goods = await this.loadGoods(user)
    ui.loading(false)

    this.calcInfo(goods, user)
    this.loadSoldNum(goods)
    this.setupTimer(goods)
  },
  onReady() {},
  onShow() {
    this.setupTimer(this.data.goods)
  },
  onHide() {
    clearInterval(this.timerId)
  },
  onPullDownRefresh() {},
  onShareAppMessage() {},
  async loadUser() {
    const user = await users.getUser()
    this.setData({
      user
    })
    return user
  },
  async loadGoods(user) {
    const time = new Date().getTime()
    const _ = dsx.cmd
    const goods = await dsx.getAll('goods', {
      promotion: _.eq(true).or(_.eq("true")),
      deadline: _.gte(time)
    })

    this.setData({
      goods
    })
    return goods
  },
  calcInfo(goods, user) {
    const vip = users.isVip(user)
    goods.forEach(ele => {
      // console.log("goods::", ele)
      let discount = 10,
        minPrice = -1,
        maxOriginPrice = -1
      ele.specList.forEach(spec => {
        const price = (vip ? spec.price : spec.vipPrice)
        const dis = Number(price) / Number(spec.originPrice) * 10
        if (dis < discount) discount = dis

        if (minPrice < 0 || price < minPrice) minPrice = price
        if (maxOriginPrice < 0 || spec.originPrice > maxOriginPrice) maxOriginPrice = spec.originPrice
      })
      // discount
      ele.discount = discount.toFixed(1)
      if (ele.discount.endsWith(".0")) ele.discount = ele.discount.slice(0, -2)
      // price
      ele.minPrice = minPrice
      ele.maxOriginPrice = maxOriginPrice
    })
    this.setData({
      goods
    })
  },
  async getSoldNum(goodsId) {
    const _ = dsx.cmd
    const res = await dsx.getAll('orders', {
      goodsList: _.elemMatch({
        spuId: _.eq(goodsId)
      })
    }, {
      goodsList: {
        num: true
      },
    })
    let soldNum = 0
    for (const order of res) {
      for (const ele of order.goodsList)
        soldNum += ele.num
    }
    return soldNum
  },
  async loadSoldNum(goods) {
    for (const ele of goods) {
      const soldNum = await this.getSoldNum(ele._id)
      ele.soldNum = soldNum
      ele.soldPercent = Number((Number(soldNum) / Number(ele.num) * 100).toFixed(0))
      ele.leftNum = Math.max(0, Number(ele.num) - soldNum)
    }
    this.setData({
      goods
    })
  },
  setupTimer(goods) {
    if (!goods) return

    const minuSec = 60,
      hourSec = minuSec * 60,
      daySec = 24 * hourSec
    const that = this
    const timeUpdater = function () {
      const nowTime = new Date().getTime()
      for (const ele of goods) {
        let timeLeft = (ele.deadline - nowTime) / 1000 // seconds
        const day = Math.floor(timeLeft / daySec)
        timeLeft -= (day * daySec)
        const hour = Math.floor(timeLeft / hourSec)
        timeLeft -= (hour * hourSec)
        const minu = Math.floor(timeLeft / minuSec)
        timeLeft -= (minu * minuSec)
        const sec = Math.floor(timeLeft)
        const timeTip = `${day}天${hour}小时${minu}分${sec}秒`
        ele.timeTip = timeTip
      }
      that.setData({
        goods
      })
    }

    clearInterval(this.timerId)
    this.timerId = setInterval(timeUpdater, 1500)
  },
  async cellTap(e) {
    const goods = ui.eventData(e, 'goods'),
      id = goods._id
    const timeNow = new Date().getTime()
    ui.loading()

    if (timeNow > goods.deadline) {
      ui.loading(false)
      return ui.toast(false, "该商品已下架")
    }
    const soldNum = await this.getSoldNum(id)
    if (soldNum >= Number(goods.num)) {
      ui.loading(false)
      return ui.toast(false, "该商品已被抢光")
    }

    nav2.goodsDetail(id, false)
  }
})